/**
 * Copyright 2017 IBM All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an 'AS IS' BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
"use strict";
const fs = require('fs');
const path = require('path');
const helper = require('./helper.js');
const logger = helper.getLogger('Create-Channel');


//Attempt to send a request to the orderer with the sendCreateChain method
const createChannel = function(channelID, channelConfigPath, username, org) {
	logger.debug('\n====== Creating Channel \'' + channelID + '\' ======\n');

	return helper.getChannelForOrg(channelID, username, org)
		.then(channel=>{
			const client = channel.getClient();

			// read in the envelope for the channel config raw bytes
			const envelope = fs.readFileSync(path.join(__dirname, channelConfigPath));
			// extract the channel config bytes from the envelope to be signed
			const channelConfig = client.extractChannelConfig(envelope);


			// sign the channel config bytes as "endorsement", this is required by
			// the orderer's channel creation policy
			let signature = client.signChannelConfig(channelConfig);

			let request = {
				config: channelConfig,
				signatures: [signature],
				name: channelID,
				orderer: channel.getOrderers()[0], // TODO: multiple orderers will fail here?
				txId: client.newTransactionID()
			};

			// send to orderer
			return client.createChannel(request);
		}).then((response) => {
			logger.debug(' response ::%j', response);
			if (response && response.status === 'SUCCESS') {
				logger.debug('Successfully created the channel.');
				let response = {
					success: true,
					message: 'Channel \'' + channelID + '\' created Successfully'
				};
				return response;
			} else {
				logger.error('\n!!!!!!!!! Failed to create the channel \'' + channelID + '\' !!!!!!!!!\n\n');
				throw new Error('Failed to create the channel \'' + channelID + '\'');
			}
	})
	.catch((err) => {
		logger.error('Failed to initialize the channel: ' + err.stack ? err.stack : err);
		throw new Error('Failed to initialize the channel: ' + err.stack ? err.stack : err);
	});
};

exports.createChannel = createChannel;
